/******************************************************************************
 * (C) 成都齐乐科技有限公司
 * 描述：网易短信接口。
 *****************************************************************************/

var crypto = require('crypto');
var https = require('https');
var querystring = require('querystring');
var TelephoneCodePlugin = require('./telephoneCodePlugin');

var TelephoneCodePlugin_Netease = TelephoneCodePlugin.extend({

    _url: "https://api.netease.im/sms/sendcode.action", // 请求接口

    /**
     * 发送验证码。
     * @param phoneNumber   电话号码
     * @param cb            回调函数
     */
    sendCode: function(phoneNumber, cb) {
        var AppKey = "efafc2e02b734902121868be7faa06fc";
        var AppSecret = "782ec2488948";
        var Nonce = Math.floor(Math.random() * 100000);
        var CurTime = Date.getStamp();

        var sha1 = crypto.createHash("sha1");
        sha1.update(AppSecret + Nonce + CurTime);
        var CheckSum = sha1.digest("hex");

        var options = {
            host: "api.netease.im",
            port: 443,
            path: "/sms/sendcode.action",
            method: "POST",
            headers: {
                "AppKey": AppKey,
                "Nonce": Nonce,
                "CurTime": CurTime,
                "CheckSum": CheckSum,
                "Content-Type": "application/x-www-form-urlencoded",
                "charset": "utf-8"
            }
        };

        var req = https.request(options, function(res){
            logger.debug("TelephoneCodePlugin_Netease: " + res.statusCode);

            res.setEncoding('utf-8');
            res.on('data', function(body){
                logger.debug("TelephoneCodePlugin_Netease: " + body);
                cb(null, JSON.parse(body));
            });
        });

        req.on('error', function(err){
            logger.debug("TelephoneCodePlugin_Netease-ERROR: " + err);
            cb(err);
        });

        req.write(querystring.stringify({
            mobile: phoneNumber,    // 手机号码
            templateid: 3122146,
            codeLen: 6              // 代码长度
        }));
        req.end();
    }

});

module.exports = new TelephoneCodePlugin_Netease();